package com.hippo.core.ui.compose.home

import LoadingDialog
import android.Manifest
import android.util.Log
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MaterialTheme.typography
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LifecycleEventEffect
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.google.accompanist.permissions.ExperimentalPermissionsApi
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import com.hippo.core.R
import com.hippo.core.core.ext.click
import com.hippo.core.core.ext.toJson
import com.hippo.core.state.DialogType
import com.hippo.core.ui.components.VerticalSpacer
import com.hippo.core.ui.compose.home.add.ConfigNetworkDialog
import com.hippo.core.ui.compose.home.add.ConfirmWifiDialog
import com.hippo.core.ui.compose.home.add.PairedResultDialog
import com.hippo.core.ui.compose.home.add.ScanDeviceDialog
import com.hippo.core.ui.navigation.AppRoute
import com.hippo.core.ui.theme.ColorBackgroundPrimary
import com.hippo.core.ui.theme.ColorBackgroundWhite
import com.hippo.core.ui.theme.PaddingMedium
import com.hippo.core.utils.AppUtil
import com.hippo.core.utils.UiHandler
import com.hippo.core.vm.HomeVM
import com.thingclips.smart.sdk.bean.DeviceBean

@OptIn(ExperimentalPermissionsApi::class)
@Composable
fun HomeScreen(navController: NavController, vm: HomeVM = viewModel()) {


    val uiState = vm.uiState

    val context = LocalContext.current


    when (uiState.dialogType) {
        is DialogType.LoadingDialog ->{
            LoadingDialog(uiState.dialogType.msg) {
                vm.updateState(uiState.copy(dialogType = DialogType.Idle))
            }
        }
        is DialogType.ScanDevice ->{
            ScanDeviceDialog(
                onDismissRequest = {vm.dismissDialog()},
                reScan = {

                },
                onFind = {scanDeviceBean ->
                    vm.updateState(uiState.copy(dialogType = DialogType.ConfigNetwork, scanDevice = scanDeviceBean))
                },
                toHelp ={
                    navController.navigate(AppRoute.FaqDetailScreen.replace("{faqId}", "3"))
                }
            )
        }
        is DialogType.ConfigNetwork ->{
            ConfigNetworkDialog(
                onDismissRequest = {vm.dismissDialog()},
                onNext = {ssid ,pwd->
                    vm.updateState(uiState.copy(dialogType = DialogType.ConfirmWifiDialog,ssid = ssid ,pwd = pwd))
                },
                toHelp = {
                    navController.navigate(AppRoute.FaqDetailScreen.replace("{faqId}", "4"))
                }
            )

        }
        is DialogType.ConfirmWifiDialog ->{
            ConfirmWifiDialog(
                ssid = uiState.ssid.orEmpty(),
                pwd = uiState.pwd.orEmpty(),
                onDismissRequest = {vm.dismissDialog()},
                onReenter = {
                    vm.updateState(uiState.copy(dialogType = DialogType.ConfigNetwork))
                },
                onConfirm = { ssid,pwd->
                    if(uiState.scanDevice != null){
                        vm.startActivator(
                            context,
                            uiState.scanDevice,
                            ssid ,
                            pwd
                        ){
                            vm.setDeviceWarn(it.devId)
                        }
                    }else{
                        Log.e("sss", "HomeScreen: uiState.scanDevice == null" )
                    }
                }
            )
        }
        is DialogType.PairedResult ->{

            if(uiState.dialogType.result){
                vm.getHomeDetail()
            }

            PairedResultDialog(
                result = uiState.dialogType.result,
                onDismissRequest = {vm.dismissDialog()},
                toHelp = {
                    vm.updateState(uiState.copy(dialogType = DialogType.Idle))
                    navController.navigate(AppRoute.FaqDetailScreen.replace("{faqId}", "5"))
                }
            )
        }
        else ->{}
    }


    val bluetoothPermissionState = rememberMultiplePermissionsState(
        listOf(
            Manifest.permission.BLUETOOTH,
            Manifest.permission.BLUETOOTH_ADMIN,
            Manifest.permission.BLUETOOTH_SCAN,
            Manifest.permission.BLUETOOTH_CONNECT,
            Manifest.permission.BLUETOOTH_ADVERTISE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION
        ),
        onPermissionsResult = {
            Log.i("HomeScreen", "onPermissionsResult: ${it.toJson()}")

            val result = it.map { it.value }.findLast { it == false }
            Log.i("HomeScreen", "HomeScreen: $result")

            if (result == null) {
                vm.updateState(uiState.copy(dialogType = DialogType.ScanDevice))
            } else {
                vm.updateState(uiState.copy(dialogType = DialogType.Idle))
                UiHandler.showToast(R.string.temp_3)
            }
        }
    )




    LifecycleEventEffect(Lifecycle.Event.ON_CREATE) {
        vm.getHomeDetail()
        vm.getBasicData()
    }


    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(ColorBackgroundPrimary)
    ) {

        Box( modifier = Modifier
            .background(ColorBackgroundWhite)
            .padding(PaddingMedium)
            .fillMaxWidth()
        ) {

            Text(
                text = stringResource(R.string.home_3),
                fontSize = 18.sp,
                fontWeight = FontWeight.Bold,
                modifier = Modifier
                    .align(Alignment.Center)
            )

            Row(
                modifier = Modifier
                    .align(Alignment.CenterEnd)
            ) {

                Box(
                    modifier = Modifier
                    .size(25.dp)
                ){
                    Image(
                        painter = painterResource(R.mipmap.home_msg),
                        contentDescription = stringResource(R.string.home_3),
                        modifier = Modifier
                            .size(20.dp)
                            .click {
                                navController.navigate(AppRoute.NotificationScreen)
                            }
                    )

                    if(uiState.hasNewMsg){
                        Spacer(modifier = Modifier.size(8.dp)
                            .background(color = Color.Red, shape = CircleShape)
                            .align(Alignment.TopEnd)
                        )
                    }

                }

                Spacer(modifier = Modifier.size(PaddingMedium))

                Image(
                    painter = painterResource(R.mipmap.add_black),
                    contentDescription = stringResource(R.string.home_3),
                    modifier = Modifier
                        .size(20.dp)
                        .click {
                            if (AppUtil.isBluetoothEnabled()) {
                                if (bluetoothPermissionState.allPermissionsGranted) {
                                    vm.updateState(uiState.copy(dialogType = DialogType.ScanDevice))
                                } else {
                                    bluetoothPermissionState.launchMultiplePermissionRequest()
                                }
                            } else {
                                UiHandler.showToast(R.string.temp_2)
                            }
                        }

                )
            }

        }


        if (uiState.loading) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .background(ColorBackgroundPrimary)
                    .padding(PaddingMedium)
            ) {
                CircularProgressIndicator(
                    modifier = Modifier
                        .align(Alignment.Center)
                )
            }

        }else if (uiState.deviceList.isNullOrEmpty()) {

            HomeEmpty {
                if (AppUtil.isBluetoothEnabled()) {
                    if (bluetoothPermissionState.allPermissionsGranted) {
                        vm.updateState(uiState.copy(dialogType = DialogType.ScanDevice))
                    } else {
                        bluetoothPermissionState.launchMultiplePermissionRequest()
                    }
                } else {
                    UiHandler.showToast(R.string.temp_2)
                }

            }
        } else {
            LazyColumn(modifier = Modifier) {
                items(uiState.deviceList.size) { index ->
                    val item = uiState.deviceList[index]
                    Log.i("sss", "HomeScreen: devId = ${item.devId}")
                    ItemDevice(item){
                        if(item.isOnline){
                            navController.navigate(AppRoute.CONTROL.replace("{devId}","${item.devId}"))
                        }else{
                            UiHandler.showToast(R.string.device_offline)
                        }
                    }
                    VerticalSpacer(PaddingMedium)
                }
            }
        }

    }

}




@Composable
private fun ItemDevice(device: DeviceBean, toDetail:(DeviceBean)->Unit) {

    Card(
        modifier = Modifier
            .padding(PaddingMedium),
        onClick = {

        }
    ) {
        Column(
            modifier = Modifier
                .background(ColorBackgroundWhite)
                .padding(PaddingMedium),
        ) {

            Row{

                Text(
                    text = device.name.orEmpty(),
                    style = TextStyle(
                        fontSize = 20.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color.Black
                    ),
                    modifier = Modifier.weight(1F))

                Text(
                    text = if(device.isOnline ) stringResource(R.string.home_4) else stringResource(R.string.home_5),
                    style = typography.titleMedium,
                    color = if(device.isOnline ) MaterialTheme.colorScheme.primary else Color.Gray,
                    modifier = Modifier.background(
                        brush = Brush.verticalGradient(
                            colors = listOf(
                                Color(0xFFFFFFFF),
                                Color(0xFFE6E6E6)
                            )
                        ),
                        shape = RoundedCornerShape(4.dp)
                    ).padding(vertical = 4.dp, horizontal = 8.dp)
                )
            }

            Image(
                painter = painterResource(R.mipmap.machine),
                contentDescription = device.name,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .padding(PaddingMedium)
                    .size(width = 170.dp, height = 100.dp)
                    .click {
                        toDetail(device)
                    }
            )

        }
    }


}


@Preview(showBackground = true)
@Composable
private fun HomeScreenPreview() {
    HomeScreen(
        navController = rememberNavController()
    )
}
